import {
 	SELECTEDHOUSE
 } from "@/store/mutations-types";
 export default {
 	namespaced: true, //其成为带命名空间的模块
 	state: {
 		selectedHouse: '',
 		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
 	},
 	mutations: {
 		increment(state, goods) {
 			state.cart.push(goods)
 			this.commit('qi_cart/saveToStorage')
 		},
 		[SELECTEDHOUSE](state, data) {
 			// state.selectedHouse = data
 		},
 		// 更新购物车中商品的勾选状态
 		updateGoodsState(state, goods) {
			console.log(goods);
 			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
 			if (findResult) {
 				findResult.goods_state = goods.goods_state
 				this.commit('qi_cart/saveToStorage')
 			}
 		},
		
 		// 更新商品的数量
 		updateGoodsCount(state, goods) {
 			const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
 			findResult.goods_count = goods.goods_count
 			this.commit('qi_cart/saveToStorage')
 		},
 		// 删除商品
 		DELETEGOODS(state, goods) {
 			state.cart = state.cart.filter(x => x.goods_id !== goods)
 			this.commit('qi_cart/saveToStorage')
 		},
		// 更新购物车中所有商品的勾选状态
		updateAllGoodsState(state, newState) {
			console.log(newState);
			console.log(state.cart);
		  state.cart.forEach(x => x.goods_state = newState)
			console.log(state.cart);
		  this.commit('qi_cart/saveToStorage')
		},
 		saveToStorage(state) {
 			uni.setStorageSync('cart', JSON.stringify(state.cart))
 		},
 	},
	getters:{
		total(state) {
		  return state.cart.reduce((total, item) => total += item.goods_count, 0)
		},
		// 购物车中已勾选商品的总数量
		checkedCount(state) {
		  return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
		},
		// 已勾选商品的总价格
		 checkedGoodsAmount(state) {
		   return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item.goods_price, 0).toFixed(2)
		 },
	},
 	actions: {
 		addDataListCart(context, goods) {
 			return new Promise(resolve => {
 				const findResult = context.state.cart.find(x => x.goods_id === goods.goods_id)
 				if (!findResult) {
 					context.commit('increment', goods)
 				} else {
 					findResult.goods_count++
 				}
 				resolve('加入成功')
 			});
 		},
  
 		// 存放token
 		// userInfo({
 		// 	state,
 		// 	commit
 		// }, val) {
 		// 	state.token = "5518"
 		// 	commit('setToken', val)
 		// },
 	},


 }
